

import { useEffect, useState } from 'react'
import { createPeopleGroup, useInterval } from '@/utils'
import './index.less'

const statusMap: any = {
  0: 'pause',
  1: 'running',
  2: 'full-weight'
}

type PeopleType = {
  weight: number,
  goodsWeight: number,
}

type PeopleGroupType = {
  peopleList: PeopleType[],
  startFloor: number,
  targetFloor: number,
  totalWeight: number,
}

type ElevatorStateType = {
  // status: 0 | 1 | 2, // 也可以使用数字代替
  arrow: 1 | -1, // 表示电梯运行的方向
  currentFloor: number, // 表示电梯当前所在的层数
  currentWeight: number, // 表示电梯当前的载重
  currentGroupList: PeopleGroupType[], // 表示当前电梯所承载的乘客信息
  hasWarnning: boolean, // 当前乘次电梯是否发出过警报
}

const Elevator = () => {

  const MaxFloor: number = 6 // 最高层
  const MinFloor: number = 1 // 最底层 最底层应该按照 1 -1 的设计，0需要排除在外
  const ElevatorFullWeight: number = 1000 // 电梯的最大载重为 1000kg

  const [elevator, setElevator] = useState<ElevatorStateType>({
    arrow: -1,
    currentFloor: 1,
    currentWeight: 0,
    currentGroupList: [],
    hasWarnning: false,
  })
  const [waitPeopleList, setWaitPeopleList] = useState<PeopleGroupType[][]>(Array.from(Array(MaxFloor), () => Array(0)))
  const [status, setStatus] = useState<number>(1)

  useInterval(() => {
    if (elevator.currentFloor === MaxFloor || elevator.currentFloor === MinFloor) {
      let _arrow: any = 0 - elevator.arrow
      setElevator({
        ...elevator,
        currentFloor: elevator.currentFloor + _arrow,
        arrow: _arrow,
        ...getCurrentGroupWeightAndGroupList(),
        hasWarnning: false,
      })
    } else {
      setElevator({
        ...elevator,
        currentFloor: elevator.currentFloor + elevator.arrow,
        ...getCurrentGroupWeightAndGroupList(),
      })
    }
  }, 5 * 1000)

  useEffect(() => {
    // createPeopleGroup()
    initWaitPeopleList()
  }, [])

  useEffect(() => {
    console.log('wait', waitPeopleList)
  }, [waitPeopleList])

  useEffect(() => {
    console.log('elevator', elevator.currentGroupList)
  }, [elevator])

  /**
   * 初始化乘员信息
   * 每一楼层随机生成npc
   */
  const initWaitPeopleList = () => {
    // 不需要管楼层，只需要管当前生成的组数的概率就行
    let gourpNumberRateList = [0, 0.4, 0.80, 0.90, 0.98]
    let _waitPeopleList = Array.from(Array(MaxFloor), () => Array(0))
    // 这里需要加上一个修正，-1 对应的 _waitList 中的 index0, 1 对应的 _waitList 中的index1
    // 假设这里没有 负楼层，先简化 那index0是什么 是 1楼等待的乘客信息嗯
    for (let floor = 0; floor < _waitPeopleList.length; floor++) {
      // 此处循环创建楼层等待的乘客，利用 createPeopleGroup() 方法，可选参数 currentFloor 来指定当前楼层
      // 这里的概率列表用来指定 当前楼层创建的乘客有多少组嗯
      let randomGroupNumber: number = (() => {
        let _random = (floor == 0 ? Math.random() * 2 : Math.random())
        // console.log('_random', _random)
        let num = 0
        for (let i = gourpNumberRateList.length - 1; i >= 0; i--) {
          if (_random > gourpNumberRateList[i]) {
            num = i
            break
          }
        }
        return num
      })()
      for (let group = 0; group < randomGroupNumber; group++) {
        let currentFloor = MinFloor + floor
        let groupPeople = createPeopleGroup(MaxFloor, MinFloor, currentFloor)
        _waitPeopleList[floor].push(groupPeople)
      }
    }
    setWaitPeopleList(_waitPeopleList)
    console.table(_waitPeopleList)
  }

  /**
   * 当前版本，每次到达一层完成上下乘客的操作
   * @returns 
   */
  const getElevatorCurrentGroup = () => {
    let _waitPeopleList: PeopleGroupType[][] = waitPeopleList
    let currentGroupList: PeopleGroupType[] = elevator.currentGroupList
    let _currentGroupList : PeopleGroupType[] = []
    let _currentWeight: number = 0
    let _hasWarnning: boolean = false

    //此楼层有等待乘客，将未超重乘客组加入电梯
    let currentFloorWaitGroupList: PeopleGroupType[] = [...waitPeopleList[elevator.currentFloor - 1]]
    let _currentFloorWaitGroupList: PeopleGroupType[] = []

    // let takeGroupWeight = 0 //每一组的重量
    // let takeGroupNumber = 0 //组数
    console.log('currentFloorWaitGroupList', currentFloorWaitGroupList)

    // 优先放乘客下电梯
    currentGroupList.forEach((item: PeopleGroupType, index: number) => {
      if (item.targetFloor !== elevator.currentFloor) {
        _currentGroupList.push(item)
        _currentWeight += item.totalWeight
      }
      if (!_hasWarnning || _currentWeight < 950) {
        setStatus(1)
      }
    })

    // 当前楼层的乘客开始上电梯
    currentFloorWaitGroupList.forEach((item: PeopleGroupType, index: number) => {
      if (_currentWeight + item.totalWeight <= 1000) {
        _currentGroupList.push(item)
        _waitPeopleList[elevator.currentFloor - 1].splice(index, 1)
        _currentWeight += item.totalWeight
      } else {
        _currentFloorWaitGroupList.push(item)
        _hasWarnning = true
      }
      if (_hasWarnning && _currentWeight >= 950) {
        setStatus(2)
      }
    })

    _waitPeopleList[elevator.currentFloor - 1] = _currentFloorWaitGroupList
    setWaitPeopleList(_waitPeopleList)

    return _currentGroupList

    // setWaitPeopleList(_waitPeopleList)

    // if(currentFloorGroupList.length > 0){
    //   currentFloorGroupList.forEach((item,index) => {
    //     // for(let i :number = 0; i < item.length ; i++ ){
    //     //   takeGroupWeight += item[i].weight
    //     // }
    //     if (elevator.currentWeight + item.totalWeight <= 950) {
    //       // 上电梯之后等待列表减去该组
    //       waitPeopleList[elevator.currentFloor - 1].splice(index,1)
    //       currentGroupList.push(currentFloorGroupList[index])
    //       takeGroupNumber++
    //       takeGroupWeight += item.totalWeight
    //     }
    //   })
    // }
    // console.log(`上电梯${takeGroupNumber}组人，重量${takeGroupWeight}kg`)
   

    // //到达目标楼层下电梯
    // let offGroupWeight = 0 //每一组的重量
    // let offGroupNumber = 0 //组数
    // elevator.currentGroupList.forEach((item, index) => {
    //   if (elevator.currentFloor == item.targetFloor) {
    //     currentGroupList.splice(index, 1)
    //     offGroupWeight++
    //     offGroupWeight += item.totalWeight
    //   }
    // })
    // console.log(`下电梯${offGroupNumber ? 1 : 0}组人，重量${offGroupWeight}kg`)
  }

  /**
   * @param toFloor 
   * @returns 
   */
  const getElevatorCurrentWeight = (groupList: PeopleGroupType[]) => {
    let currentWeight: number = 0
    //电梯乘员组没问题的话直接计算组重量就行
    groupList.forEach((item: PeopleGroupType) => {
      currentWeight += item.totalWeight
    })
    return currentWeight
  }

  /**
   * 获取电梯当前的乘员组和承载重量
   */
  const getCurrentGroupWeightAndGroupList = () => {
    let groupList = getElevatorCurrentGroup()
    console.log('currentGroupList', groupList)
    return {
      currentGroupList: groupList,
      currentWeight: getElevatorCurrentWeight(groupList),
    }
  }


  return <div className='elevator-shaft' style={{ height: `${(MaxFloor) * 120}px` }}>
    {Array(MaxFloor).fill(undefined).map((item: any, index: number) => {
      return <div className='floor-item' key={index}>
        <div className={`elevator-item${elevator.currentFloor == (MaxFloor - index) ? ` ${statusMap[status]}` : ''}`}>
          {MaxFloor - index > 0 ? MaxFloor - index : MaxFloor - index - 1}
          {elevator.currentFloor == (MaxFloor - index) && <span className='load'>载重{elevator.currentWeight}kg</span>}
        </div>
        <div className='wait-people'>
          {/* 这里修改一下，改成显示每一组以及每一组的相关信息 */}
          {/* 这一层有{waitPeopleList[MaxFloor - index - 1].length}组人在等待 */}
          {/* 重量为{everyFloorWeight[MaxFloor - MinFloor - index - 1]}kg */}
          {waitPeopleList[MaxFloor - index - 1]?.map((item: any, index: number) => {
            return <div key={index}>
              {item.peopleList.length}人重量为{item.totalWeight}kg前往{item.targetFloor}楼
            </div>
          })}

        </div>
      </div>
    })}
  </div>

}

export default Elevator 